/**
 * 
 */
package com.monkeyboy.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import com.monkeyboy.security.jwt.MyJwtTokenEnhancer;

/**
 * @Description
 *
 * @author Gavin<br>
 *         2019年9月1日
 */
@Configuration
public class TokenStoreConfig {
	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	@Bean
	@ConditionalOnProperty(prefix = "spring.oauth2.token", name = "storeType", havingValue = "redis")
	public TokenStore tokenStore() {
		return new RedisTokenStore(redisConnectionFactory);
	}

	//如果配置文件中配置了spring.oauth2.token.store-type=jwt就使用下面的设置，不然就是要上面的redis存储方式
	@Configuration
	@ConditionalOnProperty(prefix = "spring.oauth2.token", name = "storeType", havingValue = "jwt", matchIfMissing = true)
	public static class JwtTokenConfig {
		@Bean
		public TokenStore tokenStore() {
			return new JwtTokenStore(jwtAccessTokenConverter());
		}

		@Bean
		public JwtAccessTokenConverter jwtAccessTokenConverter() {
			JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
			jwtAccessTokenConverter.setSigningKey("springsecurity");// 设置加密密钥，设置在properteis里面，解密时候需要
			return jwtAccessTokenConverter;
		}

		@Bean
		@ConditionalOnMissingBean(name = "jwtTokenEnhancer")
		public TokenEnhancer jwtTokenEnhancer() {
			return new MyJwtTokenEnhancer();
		}
	}
}
